package com.lemon.core.cloud.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lemon.core.base.result.Result;
import com.lemon.core.base.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义流控异常处理器
 *
 * @author pan
 * @since 2019-07-16
 */
@Slf4j
@Component
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {

    /**
     * 服务名
     */
    @Value("${spring.application.name}")
    private String serverName;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        ResultCode resultCode = ResultCode.SYSTEM_EXECUTION_ERROR;
        // 流控（限流）
        if(e instanceof FlowException) {
            log.error("流控 FlowException", e);
            resultCode = ResultCode.FLOW_LIMITING;
        }
        // 降级
        if(e instanceof DegradeException){
            log.error("降级 DegradeException", e);
            resultCode = ResultCode.DEGRADATION;
        }
        // 参数热点异常
        if(e instanceof ParamFlowException){
            log.error("参数热点 ParamFlowException", e);
            resultCode = ResultCode.PARAM_ERROR;
        }
        // 系统异常
        if(e instanceof SystemBlockException){
            log.error("系统 SystemBlockException", e);
            resultCode = ResultCode.SYSTEM_DISASTER_RECOVERY_TRIGGER;
        }
        // 授权异常
        if(e instanceof AuthorityException){
            log.error("授权 AuthorityException", e);
            resultCode = ResultCode.AUTHORIZED_ERROR;
        }
        response.setStatus(resultCode.getCode());
        response.setContentType("application/json;charset=utf-8");
        // 系统繁忙信息
        String errorSystemMsg = this.serverName + ": " + resultCode.getMsg();
        Result<String> result = Result.failed(resultCode, errorSystemMsg);
        new ObjectMapper().writeValue(response.getWriter(), result);
    }

}
